package com.tfswx.fljdmxyy.config;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

/**
 * 系统配置
 *
 * @author 李航
 * @date 2022/8/12
 **/
@Slf4j
public class SystemProcessorConfig implements EnvironmentPostProcessor {
    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        // 1.获取所有配置源
        MutablePropertySources propertySources = environment.getPropertySources();

        // 2.遍历配置源，获取数据库配置
        String jdbcUrl = null;
        String username = null;
        String password = null;
        for (PropertySource<?> propertySource : propertySources) {
            // 2.1获取数据库地址
            Object url = propertySource.getProperty("spring.datasource.url");
            if (!StrUtil.isBlankIfStr(url) && StrUtil.isBlank(jdbcUrl)) {
                jdbcUrl = String.valueOf(url);
                // 2.2如果是sqlite数据库，则不需要再获取用户名和密码
                if (jdbcUrl.startsWith("jdbc:sqlite")) {
                    break;
                }
            }

            // 2.3获取数据库用户名
            Object user = propertySource.getProperty("spring.datasource.username");
            if (!StrUtil.isBlankIfStr(user) && StrUtil.isBlank(username)) {
                username = String.valueOf(user);
            }

            // 2.4获取数据库访问密码
            Object pwd = propertySource.getProperty("spring.datasource.password");
            if (!StrUtil.isBlankIfStr(pwd) && StrUtil.isBlank(password)) {
                password = String.valueOf(pwd);
            }

            // 2.5都获取到后就退出
            if (StrUtil.isAllNotBlank(jdbcUrl, username, password)) {
                break;
            }
        }

        // 3.创建数据库连接，获取系统配置
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(jdbcUrl, username, password);
            Statement statement = conn.createStatement();
            String sql = "SELECT * FROM t_pz_xt_pz WHERE sfsc = 'N' AND pzxlx = '1'";
            ResultSet resultSet = statement.executeQuery(sql);

            // 4.新建配置源，并将该配置源添加到系统配置的第一个
            Properties properties = new Properties();
            while (resultSet.next()) {
                properties.setProperty(resultSet.getString("pzxbm"), resultSet.getString("pzxz"));
            }
            propertySources.addFirst(new PropertiesPropertySource("application.properties", properties));
        } catch (Exception e) {
            log.error("配置项加载出错：", e);
        } finally {
            try {
                conn.close();
            } catch (Exception e) {
                log.error("数据库连接关闭失败", e);
            }
        }
    }
}
